package org.micode.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteWatchdog;
import org.apache.commons.exec.PumpStreamHandler;

import java.io.ByteArrayOutputStream;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

@Slf4j
public class OsProcessUtils {

    public static String getLocalIp() {
        try {
            String hostAddress = null;
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();
                if (networkInterface.getName().equals("lo")) {
                    continue;
                }
                Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
                while (inetAddresses.hasMoreElements()) {
                    InetAddress inetAddress = inetAddresses.nextElement();
                    if (inetAddress instanceof Inet4Address) {
                        hostAddress = inetAddress.getHostAddress();
                        break;
                    }
                }
                if (hostAddress != null) {
                    break;
                }
            }
            return hostAddress;
        } catch (Exception e) {
            return "";
        }
    }

    public static boolean exec(String cmd,
                               String[] params,
                               int timeoutSeconds,
                               String cmdName) {
        boolean success;
        try {
            log.info(cmdName + " " + cmd + " \n " + StringExtUtils.arrayToString(params));

            final int okExitValue = 0;

            final CommandLine commandLine = new CommandLine(cmd);
            commandLine.addArguments(params, false);

            ExecuteWatchdog watchdog = new ExecuteWatchdog(timeoutSeconds * 1000);

            DefaultExecutor executor = new DefaultExecutor();
            executor.setWatchdog(watchdog);
            executor.setExitValue(okExitValue);

            ByteArrayOutputStream outputStream = null;
            ByteArrayOutputStream errorStream = null;
            if (log.isDebugEnabled() || log.isTraceEnabled()) {
                outputStream = new ByteArrayOutputStream();
                errorStream = new ByteArrayOutputStream();
                PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream, errorStream);
                executor.setStreamHandler(streamHandler);
            }

            int exitValue = executor.execute(commandLine);
            if (log.isDebugEnabled() || log.isTraceEnabled()) {
                if (null != outputStream) {
                    String out = outputStream.toString("UTF-8");
                    String error = errorStream.toString("UTF-8");
                    log.debug("正常输出: {}", out);
                    log.warn("异常输出: {}", error);
                }
            }

            if (exitValue != okExitValue) {
                success = false;
                //说明命令执行失败
                log.warn(cmdName + " execution failed: {}!", exitValue);
            } else {
                success = true;
                log.debug(cmdName + " execution ok!");
            }

        } catch (Exception e) {
            success = false;
            log.error(cmdName + " execution error", e);
        }
        return success;
    }

    public static boolean exec(String cmd, int timeoutSeconds, String cmdName) {
        boolean success;
        try {
            log.info(cmdName + " " + cmd + "\n");

            final int okExitValue = 0;
            final CommandLine commandLine = CommandLine.parse(cmd);
            ExecuteWatchdog watchdog = new ExecuteWatchdog(timeoutSeconds * 1000);
            DefaultExecutor executor = new DefaultExecutor();
            executor.setWatchdog(watchdog);
            executor.setExitValue(okExitValue);

            int exitValue = executor.execute(commandLine);
            if (exitValue != okExitValue) {
                success = false;
                //说明命令执行失败
                log.warn(cmdName + " execution failed: {}!", exitValue);
            } else {
                success = true;
                log.debug(cmdName + " execution ok!");
            }
        } catch (Exception e) {
            success = false;
            log.error(cmdName + " execution error", e);
        }
        return success;
    }

}
